check if directory exists python

93

python check if path does not exist -

import os
if not os.path.exists('my_folder'):
    os.makedirs('my_folder')

python check if file exists -

import os

os.path.exists("file.txt") # Or folder, will return true or false

python check if folder exists -

import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))

how to check whether file exists in python -

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")

check if directory exists python -

>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

Comments

Submit
0 Comments